<template>
  <el-dialog
    v-el-drag-dialog
    title="新增盘点"
    :visible.sync="visible"
    width="1200px"
  >
    <el-form ref="form" class="form" :model="form" :inline="true" label-width="80px">
      <el-form-item label="仓库名称" prop="storeId">
        <el-select v-model="form.storeId" placeholder="请选择" @change="changeStoreId">
          <!-- <el-option label="请选择" :value="0" /> -->
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点人员" prop="name">
        <el-input :value="userInfo.userName" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="盘点日期">
        <el-date-picker v-model="form.date" type="date" disabled />
      </el-form-item>
      <el-form-item style="width: 100%;" label="备注" prop="name">
        <el-input v-model="form.remark" style="width: 100%;" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品类型" prop="csmTypeSource">
        <el-tree-select
          v-model="shop.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择商品分类',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-select v-model="shop.goodsId" placeholder="请选择" @change="selectGoods">
          <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
        </el-select>
      </el-form-item>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >添加</el-button>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      height="350"
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      @selection-change="handleSelectionChange"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" @click="save">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { goodsTypeQueryList, goodsTypeDetail, queryMap, repertoryStoreAdd, repertoryStoreDeatil } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { formatColumnMap } from '@/utils'
  export default {
    name: 'add',
    props: ['storeMap'],
    data() {
      return {
        visible: false,
        form: {
          date: new Date()
        },
        statusMap: [],
        uuid: 1,
        selectTableData: [],
        goodsDetail: {},
        goodsTypesDetailList: [],
        goodsTreeData: [],
        gtObj: {},
        shop: {
          goodsId: null,
          gtId: null
        },
        tableData: {
          column: [
            {
              type: 'selection'
            },
            {
              prop: 'gtName',
              label: '商品类型'
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              renderHeader: (h, { row }) => {
                return (
                <el-tooltip
                  class='item'
                  effect='dark'
                  content='默认加载仓库中有数据的商品，可在上方选择其他商品点击添加'
                  placement='top-start'
                >
                  <i class='el-icon-question'>
                    <span>商品名称</span>
                  </i>
                </el-tooltip>
                )
              }
            },
            {
              prop: 'goodsSpec',
              label: '规格型号'
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, scope) => (

              <div>
                  {scope.row._edit && !scope.row.storeName ? (
                    <el-select value={ scope.row[scope.column.property] }
                          style='width: 80px'
                          onChange={ (val) => { scope.row[scope.column.property] = val } }>
                          {
                            scope.row.statusMap.map(option => {
                              return (
                                <el-option label={ option.desc } value={ option.value }></el-option>
                              )
                            })
                          }
                        </el-select>
                  ) : (
                      <span>
                        {scope.row.gdStatus &&
                          formatColumnMap(
                            this.statusMap,
                            'value',
                            scope.row.gdStatus,
                            'desc'
                          )}
                      </span>
                  )}
                </div>

            )
            },
            {
              prop: 'gdCount',
              label: '账面库存',
              render: (h, { row }) => {
                return <span>{row.gdCount + row.unitName}</span>
              }
            },
            {
              prop: 'realCount',
              label: '实际库存',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '盈/亏数量',
              render: (h, { row, $index }) =>
                row.realCount - row.gdCount === 0 ? (
                <span></span>
                  ) : (
                <span style='color:red'>
                  {row.realCount - row.gdCount > 0
                    ? '+' + (row.realCount - row.gdCount)
                    : row.realCount - row.gdCount}
                </span>
              )
            },
            {
              prop: 'remark',
              label: '备注',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-button
                        type='primary'
                        onClick={() => {
                          this.handleSave(scope)
                        }}
                      >
                        保存
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.handleCancle(scope)
                        }}
                      >
                        取消
                      </el-button>
                    </div>
                  ) : (
                    <el-button
                      type='primary'
                      onClick={() => {
                        this.handleEdit(scope)
                      }}
                    >
                      编辑
                    </el-button>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData',
        'userInfo'
      ])
    },
    methods: {
      async open(row) {
        await this.getGoodsTreeData()
        await this.getGoodStatus()
        this.visible = true
      },
      // 获取商品状态枚举
      async getGoodStatus() {
        //  GdStatus
        const res = await queryMap({ enumName: 'GdStatus' })
        this.statusMap = res.data
      },
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        // console.log(res, 'res')
        // var list = [res.data.find(l => l.gtId === 192)]
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data)
      },
      // 选择商品分类
      async selectTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        this.gtObj = { ...value }
        this.shop.goodsId = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          if (res.exc != null) { this.$messsage.error('查询异常'); return } else if (!res.data) { this.$messsage.error('没有查询到相关数据'); return }
          var array = []
          if (this.corpSettingData.sp3 >> 6 & 0x01) {
            array = array.concat(res.data.rows.filter(function(item) {
              if (!item.options) {
                return true
              }
              if (item.options >> 1 & 0x01) {
                return false
              }
              if (item.options >> 2 & 0x01) {
                return false
              }
              return true
            }))
          } else {
            if (this.gtObj && this.gtObj.gtFlag === 1) {
              array = array.concat(res.data.rows.filter(function(item) {
                return item.pricingMode === 2
              }))
            } else {
              array = array.concat(res.data.rows)
            }
          }

          this.goodsTypesDetailList = [...array]
          // this.goodsTypesDetailList = res.data.rows
          // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      // 查询库存详情
      async changeStoreId(val) {
        const params = {
          storeId: val,
          currentPage: 1,
          pageSize: 999,
          sortBy: -1
        }
        const res = await repertoryStoreDeatil(params)
        var list = res.data.rows.map(l => {
          return { ...l, gdCount: l.netWeight * 1, realCount: l.netWeight * 1, remark: null }
        })

        this.tableData.data = list
        console.log(res)
      },

      // 添加商品
      addShop() {
        var { gtId, goodsId, gdCount } = this.temp
        if (!(gtId && goodsId && gdCount)) {
          this.$message.warning('请完整商品属性')
          return
        }
        var goodsName = this.goodsTypesDetailList.find(l => l.goodsId === this.temp.goodsId).goodsName
        var item = this.tableData.data.find(l => l.goodsId === this.temp.goodsId)
        if (item) {
          item.gdCount++
        } else {
          var obj = {
            gdCount: '1',
            gdStatus: 2,
            goodsId: goodsId,
            goodsName: goodsName,
            gtId: gtId,
            gtName: '钢瓶',
            rowid: new Date() * 1
          }
          this.tableData.data.push(obj)

          // this.tableData.data = [...this.tableData.data, { gtName: this.temp.gtName, goodsName: this.temp.goodsName, gdCount: this.temp.gdCount }]
        }
      },
      // 删除商品
      del(row, index) {
        const vm = this
        vm.$confirm('是否将该商品移除列表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.tableData.data.splice(index, 1)
            // this.$message.success('删除成功')
          })
          .catch((e) => {
            // this.$message.info('已取消删除操作')
          })
      },
      selectGoods(val) {
        console.log(val)
        var obj = this.goodsTypesDetailList.find(l => l.goodsId === val)
        console.log({ ...obj })
        this.goodsDetail = { ...obj }
      },
      // 当前选择的表格行
      handleSelectionChange(val) {
        console.log(val, '当前选择的表格行')
        this.selectTableData = val
      },
      add() {
        // if (!this.form.storeId) {
        //   this.$message.warning('请选择仓库名称')
        //   return
        // }
        // if (!(this.shop.gtId && this.shop.goodsId)) {
        //   this.$message.warning('请选择商品')
        //   return
        // }

        const selectedGd = this.goodsDetail
        var row = {
          uuid: ++this.uuid,
          goodsId: selectedGd.goodsId,
          goodsName: selectedGd.goodsName,
          gtId: selectedGd.gTypeId,
          gtName: selectedGd.gtName,
          gtSNNo: selectedGd.gtSNNo,
          pricingMode: selectedGd.pricingMode,
          goodsCode: selectedGd.goodsCode,
          specCode: selectedGd.specCode,
          goodsSpec: selectedGd.specName,
          unitId: selectedGd.unitId,
          unitName: selectedGd.unitName,
          goodStatus: selectedGd.gdStatus,
          gdCount: 0,
          realCount: 0,
          lessCount: 0,
          netWeight: 0,
          realNetWeight: 0,
          remark: null,
          statusMap: this.statusMap.filter(item => (1 << item.value & selectedGd.gdStatus) > 0),
          gdStatus: null,
          _edit: true
        }
        if (row.pricingMode === 2) {
          row.statusMap = [{ value: 6, desc: '正常' }]
        }
        // console.log(this.statusMap.filter(item => (1 << item.value & selectedGd.gdStatus) > 0))
        this.tableData.data.push(row)
        this.tableData.defaultData.push(row)
        this.$refs.lbTable.toggleRowSelection(row) // 默认添加选中
        console.log(row)
        console.log(selectedGd, 'selectedGd')
        // _this.grid_check.datagrid('insertRow', {
        //   index: 0,
        //   row: row
        // })
        // _this.grid_check.datagrid('selectRow', 0)
      },
      lessCountFormat(r) {
        var lessCount = r.realCount - r.gdCount
        if (!lessCount) {
          return ''
        }
        if (r.pricingMode === 2) {
          lessCount = Number(lessCount).toFixed(2)
        }
        return (lessCount > 0 && !lessCount) ? lessCount : ''
      },
      handleEdit(scope) {
        if (scope.row.gdStatus) {
          this.$set(scope.row, 'statusMap', this.statusMap.filter(item => (1 << item.value & scope.row.gdStatus.gdStatus) > 0))
        } else {
          this.$set(scope.row, 'statusMap', this.statusMap.filter(item => (1 << item.value & this.goodsDetail.gdStatus) > 0))
        }
        this.$set(scope.row, '_edit', true)

        console.log(scope)
      },
      handleSave(scope) {
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
      },
      handleCancle(scope) {
        this.tableData.data[scope.$index] = JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
        scope.row._edit = false
        // this.$set(
        //   this.tableData.data,
        //   scope.$index,
        //   JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
        // )
      },

      async save() {
        var storeId = this.form.storeId
        if (!this.form.storeId) {
          this.$message.warning('请选择仓库名称')
          return
        }
        var storeName = this.storeMap.find(l => l.storeId === this.form.storeId).storeName

        var createUser = this.userInfo.userName
        if (!createUser) {
          this.$message.error('请输入盘点人员')
          return
        }

        var remark = this.form.remark
        // var rows = this.tableData.data
        var rows = this.selectTableData
        if (!rows || !rows.length) {
          this.$message.error('请选择需盘点商品')
          return
        }
        var goodsIdObj = {} // 判断某种状态的商品是否重复 { goodsId: [gdStatus1, gdStatus2] }
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i]
          if (!row.gdStatus) {
            this.$message.error(this.StringFormat('请选择{0}的状态', row.goodsName))
            return
          }
          if (!goodsIdObj[row.goodsId]) {
            goodsIdObj[row.goodsId] = [row.gdStatus * 1]
          } else {
            console.log(goodsIdObj[row.goodsId], 'goodsIdObj[row.goodsId]')
            if (goodsIdObj[row.goodsId].find(l => l === row.gdStatus * 1)) {
              this.$message.error(this.StringFormat('{0}（{1}）已存在', row.goodsName, this.statusFormat(row.gdStatus)))
              return
            } else {
              goodsIdObj[row.goodsId].push(row.gdStatus * 1)
            }
          }
          if (!row.gdCount && (!row.realCount || row.realCount * 1 === 0)) {
            this.$message.error(this.StringFormat('请输入{0}的实际库存', row.goodsName, this.statusFormat(row.gdStatus)))
            return
          }
          if (row.storeName && (row.realCount >= 0 || row.gdCount >= 0)) {
            if (!row.gdCount) row.gdCount = 0
            if (row.realCount * 1 !== row.gdCount * 1) {
              if (!row.remark) {
                this.$message.error(this.StringFormat('{0} 的账面库存和实际库存不相等，请在备注里写明原因', row.goodsName, this.statusFormat(row.gdStatus)))
                return
              }
            }
          }
        }
        var newRows = []
        for (i = 0; i < rows.length; i++) {
          var obj = { ...rows[i] }
          if (obj.pricingMode === 2) {
            obj.netWeight = obj.realCount
            obj.gdCount = 0
            obj.realCount = 0
          } else {
            obj.gdCount = obj.realCount
          }
          delete obj.realCount
          delete obj.realNetWeight
          newRows.push(obj)
        }
        var checkBill = {
          storeId: storeId,
          storeName: storeName,
          remark: remark,
          detailList: newRows
        }
        console.log(checkBill, 'checkBill')
        const res = await repertoryStoreAdd(checkBill)
        if (res.exc != null) {
          this.$message.error(res.exc || '操作异常')
          return
        }
        this.$message.info(res.data)
        this.$emit('refresh')
        this.reset()
      },
      StringFormat(B) {
        var A = Array.prototype.slice.call(arguments, 1)
        return B.replace(/\{(\d+)\}/g, function(C, D) {
          return A[D]
        })
      },
      statusFormat(val, rowData, rowIndex) {
        var msg = this.statusMap[val] || ''
        return msg
      },
      reset() {
        this.tableData.data = []
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
